package com.whoops.cloud.security.controller;

import com.whoops.cloud.security.entity.User;
import com.whoops.cloud.security.tool.JwtUtil;
import com.whoops.cloud.security.tool.RedisUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
public class LginController {

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/login")
    public String login(){
        return "lgin";
    }

    @RequestMapping("/success")
    public String success(HttpServletRequest request, HttpServletResponse response){
        //获取当前用户
        User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //生成token
        String token = JwtUtil.createToken(user);
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies){
            if (StringUtils.equals(cookie.getName(),"ZuulToken")){
                redisUtil.set(cookie.getValue(),token,JwtUtil.EXPIRE);
            }
//            System.out.println("security"+cookie.getName());
        }
//        return "redirect:/web/product/productList";
        return "success";
    }

}
